const themes = {};

themes['global-default'] = new URL('@/assets/style/global/default.css', import.meta.url).href;
themes['global-blue'] = new URL('@/assets/style/global/blue.css', import.meta.url).href;
themes['global-green'] = new URL('@/assets/style/global/green.css', import.meta.url).href;
themes['global-purple'] = new URL('@/assets/style/global/purple.css', import.meta.url).href;
themes['global-red'] = new URL('@/assets/style/global/red.css', import.meta.url).href;

themes['menu-default'] = new URL('@/assets/style/menu/default.css', import.meta.url).href;
themes['menu-black'] = new URL('@/assets/style/menu/black.css', import.meta.url).href;
themes['menu-grey'] = new URL('@/assets/style/menu/grey.css', import.meta.url).href;

export const loadTheme = (type, theme) => {
    const oldLink = document.querySelector(`link[data-${type}-theme]`);
    if (oldLink) {
        document.head.removeChild(oldLink);
  }

    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = themes[type + "-" + theme];
    link.setAttribute(`data-${type}-theme`, theme);
    document.head.appendChild(link);
};

// 处理主题样式
export const changePrimaryStyle = (theme) => {
    document.documentElement.style.setProperty('--el-color-primary', theme);
  for (let i = 1; i <= 9; i++) {
        document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, `${getLightColor(theme, i / 10)}`);
  }
  for (let i = 1; i <= 9; i++) {
        document.documentElement.style.setProperty(`--el-color-primary-dark-${i}`, `${getDarkColor(theme, i / 10)}`);
  }
};

// hex颜色转rgb颜色
export const hexToRgb = (str) => {
  str = str.replace('#', '');
  const hex = str.match(/../g);
  for (let i = 0; i < 3; i++) {
    if (hex) {
      hex[i] = String(parseInt(hex[i], 16));
    }
  }
  return hex ? hex : [];
};

// 变浅颜色值
export const getLightColor = (color, level) => {
  if (!color) return '';
  const rgb = hexToRgb(color);
  for (let i = 0; i < 3; i++) {
    const s = (255 - Number(rgb[i])) * level + Number(rgb[i]);
    rgb[i] = String(Math.floor(s));
  }
  return rgbToHex(rgb[0], rgb[1], rgb[2]);
};

// 变深颜色值
export const getDarkColor = (color, level) => {
  if (!color) return '';
  const rgb = hexToRgb(color);
  for (let i = 0; i < 3; i++) {
    rgb[i] = String(Math.floor(Number(rgb[i]) * (1 - level)));
  }
  return rgbToHex(rgb[0], rgb[1], rgb[2]);
};

// rgb颜色转Hex颜色
export const rgbToHex = (r, g, b) => {
  const hex = [Number(r).toString(16), Number(g).toString(16), Number(b).toString(16)];
  for (let i = 0; i < 3; i++) {
    if (hex[i].length === 1) {
      hex[i] = `0${hex[i]}`;
    }
  }
  return `#${hex.join('')}`;
};